package com.dm.dao.impl;

import com.dm.dao.BaseDao;
import com.dm.dao.FileDao;
import com.dm.dto.FileAttributeDto;
import com.dm.dto.FilesDto;
import com.dm.dto.input.FileDto;
import com.dm.dto.input.FileSearchDto;
import com.dm.dto.input.UserDto;
import com.dm.entity.File;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author hqw521@qq.com
 * @date 2018/11/16 13:23
 */
@Repository
public class FileDaoImpl implements FileDao {
    @Autowired
    private BaseDao baseDao;

    @Override
    public Integer insertFile(FileDto fileDto) {
        String sql = "insert into dm_file (file_name, file_keyWord, file_theme, folder_id, user_id, file_path, relative_path, file_size) values (?, ?, ?, ?, ?, ?, ?, ?)";
        Query query = baseDao.getSession().createSQLQuery(sql);
        query.setString(0, fileDto.getFileName());
        query.setString(1, fileDto.getFileKeyWord());
        query.setString(2, fileDto.getFileTheme());
        query.setInteger(3, fileDto.getFolderId());
        query.setInteger(4, fileDto.getUserId());
        query.setString(5, fileDto.getFilePath());
        query.setString(6, fileDto.getRelativePath());
        query.setDouble(7, fileDto.getFileSize());
        return query.executeUpdate();
    }

    @Override
    public List<File> findFiles(UserDto userDto) {
        String hql = "from File f where f.dmUserByUserId.userId = " + userDto.getUserId();
        Query query = this.baseDao.getSession().createQuery(hql);
        List<File> files = query.list();
        return files;
    }

    @Override
    public List<FilesDto> findFilesByFolder(Integer userId, Integer folderId) {
        String sql = "SELECT\n" +
                "\tdf.file_id fileId,\n" +
                "\tdf.file_name fileName,\n" +
                "\tdf.file_size fileSize,\n" +
                "\tdf.click_number clickNumber,\n" +
                "\tdf.relative_path relativePath,\n" +
                "\tdf.user_id userId,\n" +
                "\tconcat(\n" +
                "\t\tdf.create_time,\n" +
                "\t\t' ',\n" +
                "\t\tdu.user_name\n" +
                "\t) updateMsg\n" +
                "FROM\n" +
                "\tdm_file df\n" +
                "LEFT JOIN dm_user du ON du.user_id = df.user_id\n" +
                "WHERE\n" +
                "\tdf.folder_id = " + folderId;
        Query query = this.baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(FilesDto.class));
        List<FilesDto> files = query.list();
        return files;
    }

    @Override
    public Integer fileRename(String fileName, Integer fileId) {
        String hql = "update File f set f.fileName = '" + fileName + "' where f.fileId = " + fileId;
        Query query = this.baseDao.getSession().createQuery(hql);
        return query.executeUpdate();
    }

    @Override
    public Integer deleteFiles(Integer[] ids) {
        String hql = "delete File f where f.fileId in (:ids)";
        Query query = this.baseDao.getSession().createQuery(hql);
        return query.setParameterList("ids", ids).executeUpdate();
    }

    @Override
    public List<String> findFileName(Integer[] ids) {
        String hql = "select f.fileName from File f where f.fileId in (:ids)";
        Query query = this.baseDao.getSession().createQuery(hql);
        query.setParameterList("ids", ids);
        List<String> list = query.list();
        return list;
    }

    @Override
    public List<FilesDto> fileSearch(FileSearchDto fileSearchDto) {
        StringBuffer sql = new StringBuffer("SELECT\n" +
                "\tdf.file_id fileId,\n" +
                "\tdf.file_name fileName,\n" +
                "\tdf.file_size fileSize,\n" +
                "\tdf.click_number clickNumber,\n" +
                "\tconcat(\n" +
                "\t\tdf.create_time,\n" +
                "\t\t' ',\n" +
                "\t\tdu.user_name\n" +
                "\t) updateMsg\n" +
                "FROM\n" +
                "\tdm_file df\n" +
                "LEFT JOIN dm_user du ON du.user_id = df.user_id\n" +
                "WHERE 1=1");
        if (fileSearchDto.getFileName() != null && !fileSearchDto.getFileName().equals("")) {
            sql.append(" and df.file_name like '%" + fileSearchDto.getFileName() + "%'");
        }
        if (fileSearchDto.getFileTheme() != null && !fileSearchDto.getFileTheme().equals("")) {
            sql.append(" and df.file_theme like '%" + fileSearchDto.getFileTheme() + "%'");
        }
        if (fileSearchDto.getFileKeyWord() != null && !fileSearchDto.getFileKeyWord().equals("")) {
            sql.append(" and df.file_keyWord like '%" + fileSearchDto.getFileKeyWord() + "%'");
        }
        if (fileSearchDto.getUserId() != null) {
            sql.append(" and df.user_id = " + fileSearchDto.getUserId());
        }
        if (fileSearchDto.getStartDate() != null && !fileSearchDto.getStartDate().equals("")) {
            sql.append(" and df.create_time >= " + fileSearchDto.getStartDate());
        }
        if (fileSearchDto.getEndDate() != null && !fileSearchDto.getEndDate().equals("")) {
            sql.append(" and df.create_time <= " + fileSearchDto.getEndDate());
        }
        Query query = this.baseDao.getSession().createSQLQuery(sql.toString()).setResultTransformer(Transformers.aliasToBean(FilesDto.class));
        List<FilesDto> filesDtos = query.list();
        return filesDtos;
    }

    @Override
    public FileAttributeDto findFileAttribute(Integer fileId) {
        String sql = "select file_size size, create_time createTime, update_time updateTime from dm_file where file_id = " + fileId;
        Query query = this.baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(FileAttributeDto.class));
        List<FileAttributeDto> list = query.list();
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public void updateClickNum(Integer fileId) {
        String sql = "update dm_file df set df.click_number = df.click_number + 1 where df.file_id = " + fileId;
        Query query = this.baseDao.getSession().createSQLQuery(sql);
        query.executeUpdate();
    }

    @Override
    public List<FileDto> findFileNameAndPath(Integer[] ids) {
        String sql = "select df.file_name fileName, df.relative_path relativePath from dm_file df where df.file_id in (";
        for (Integer id : ids) {
            sql += id + ",";
        }
        sql = sql.substring(0, sql.lastIndexOf(","));
        sql += ")";
        Query query = this.baseDao.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(FileDto.class));
        List<FileDto> list = query.list();
        return list;
    }
}
